<template>
	<view class="content">
		<scroll-view
			scroll-y
			class="task-scroll-view"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="task-list" v-if="taskList.length > 0">
				<view class="task-item" v-for="task in taskList" :key="task.taskId" @click="goToTaskDetail(task.taskId)">
					<image class="task-image" :src="getFirstImageUrl(task)" mode="contain" @error="imageError"></image>
					<view class="job-title-line">{{ task.jobName }}</view>
					<view class="job-info-row">
						<view class="job-info-left">{{ formatJobInfo(task) }}</view>
						<view class="job-info-right">预算: ¥{{ task.price }}{{ getSalaryUnit(task) }}</view>
					</view>
					<view class="task-info">
						<text class="task-title">{{ task.title }}</text>
					</view>
				</view>
			</view>
			<view v-else class="empty-tip">
				<text>去关注你感兴趣的人吧，看看他们会发布什么任务</text>
			</view>
		</scroll-view>
		<!-- 发布弹窗 -->
		<view v-if="showPublishPopup" class="custom-popup-mask" @click="closePublishPopup">
			<view class="custom-popup" @click.stop>
				<view class="popup-item" @click="onChooseAlbum">从相册选择</view>
				<view class="popup-item" @click="onTakePhoto">
					相机
					<text class="popup-desc">拍摄与直播</text>
				</view>
				<view class="popup-item" @click="onTextGenerate">写文字</view>
				<view class="popup-cancel" @click="closePublishPopup">取消</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getFollowedUserTasks } from '@/api/task.js';
import config from '@/config/config.js';
import { mapGetters } from 'vuex';

export default {
	data() {
		return {
			taskList: [],
			loading: false,
			isRefreshing: false,
			showPublishPopup: false,
		};
	},
	computed: {
		...mapGetters('user', ['userInfo', 'isLogin'])
	},
	onShow() {
		this.loadFollowedTasks();
		this.showPublishPopup = false;
	},
	mounted() {
		uni.onTabBarMidButtonTap(() => {
			const pages = getCurrentPages();
			if (pages.length > 0) {
				const currentPage = pages[pages.length - 1];
				console.log('Current page route in follow.vue:', currentPage.route);
				if (currentPage.route === 'pages/tabbar/follow/follow') {
					this.showPublishPopup = true;
				}
			}
		});
	},
	methods: {
		async loadFollowedTasks() {
			if (this.loading) return;
			this.loading = true;
			try {
				const response = await getFollowedUserTasks();
				if (response.code === 200) {
					this.taskList = response.rows || [];
				} else {
					uni.showToast({
						title: response.msg || '加载失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取关注用户任务失败:', error);
				uni.showToast({
					title: '网络异常，请稍后再试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				this.isRefreshing = false;
			}
		},
		onRefresh() {
			this.isRefreshing = true;
			this.loadFollowedTasks();
		},
		goToTaskDetail(taskId) {
			// 检查当前用户是否为任务发布者
			const currentTask = this.taskList.find(task => task.taskId == taskId);
			if (currentTask && this.userInfo && currentTask.createBy == this.userInfo.userId) {
				// 如果是发布者，跳转到管理页面
				uni.navigateTo({
					url: `/pages/task-manage/task-manage?taskId=${taskId}`
				});
			} else {
				// 如果是普通用户，跳转到详情页面
				uni.navigateTo({
					url: `/pages/task-detail/task-detail?taskId=${taskId}`
				});
			}
		},
		getFirstImageUrl(task) {
			if (task.imageUrls) {
				const imageUrlsArray = task.imageUrls.split(',');
				const firstImage = imageUrlsArray[0];
				if (firstImage) {
					if (firstImage.startsWith('http')) {
						return firstImage;
					}
					return config.baseUrl + config.apiPrefix + firstImage;
				}
			}
			return '/static/images/default-image.png';
		},
		formatJobInfo(task) {
			const info = [];
			if (task.cityName) info.push(task.cityName);
			if (task.experienceName) info.push(task.experienceName);
			if (task.educationName) info.push(task.educationName);
			return info.join(' | ');
		},
		getSalaryUnit(task) {
			if (task.salaryType === '0') return '/天';
			if (task.salaryType === '1') return '/月';
			if (task.salaryType === '2') return '/总';
			return '';
		},
		imageError(e) {
			// console.error('图片加载失败:', e.detail.errMsg);
		},
		closePublishPopup() {
			this.showPublishPopup = false;
		},
		onChooseAlbum() {
			this.closePublishPopup();
			uni.chooseImage({
				count: 1,
				sourceType: ['album'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					uni.navigateTo({
						url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
					});
				}
			});
		},
		onTakePhoto() {
			this.closePublishPopup();
			uni.chooseImage({
				count: 1,
				sourceType: ['camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					uni.navigateTo({
						url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
					});
				}
			});
		},
		onTextGenerate() {
			this.closePublishPopup();
			uni.navigateTo({
				url: '/pages/text-input/text-input'
			});
		}
	}
};
</script>

<style scoped>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100vh;
	box-sizing: border-box;
}

.task-scroll-view {
	width: 100%;
	height: 100%;
	background-color: #f7f7f7;
}

.task-list {
	padding: 10rpx;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.task-item {
	background-color: #fff;
	border-radius: 10rpx;
	width: calc(50% - 10rpx);
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	overflow: hidden;
	display: flex;
	flex-direction: column;
	font-size: 26rpx;
}

.task-image {
	width: 100%;
	height: 280rpx;
	background-color: #eee;
}

.job-title-line {
	padding: 10rpx 16rpx;
	font-weight: bold;
	font-size: 28rpx;
	color: #333;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.job-info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 16rpx;
	font-size: 24rpx;
	color: #666;
}

.job-info-left {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.job-info-right {
	font-weight: bold;
	color: #ff5722;
	white-space: nowrap;
}

.task-info {
	padding: 10rpx 16rpx;
}

.task-title {
	font-size: 24rpx;
	color: #999;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	text-overflow: ellipsis;
	line-height: 1.4;
	height: 2.8em;
}

.empty-tip {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400rpx;
	color: #999;
}
.custom-popup-mask {
	position: fixed;
	left: 0; right: 0; top: 0; bottom: 0;
	background: rgba(0,0,0,0.3);
	z-index: 9999;
	display: flex;
	align-items: flex-end;
}
.custom-popup {
	width: 100vw;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding-bottom: 40rpx;
}
.popup-item {
	padding: 40rpx 0 20rpx 0;
	text-align: center;
	font-size: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}
.popup-desc {
	display: block;
	font-size: 20rpx;
	color: #999;
	margin-top: 8rpx;
}
.popup-cancel {
	padding: 40rpx 0 0 0;
	text-align: center;
	font-size: 30rpx;
	color: #007aff;
}
</style>
